<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">



      <el-form-item label="编号" prop="modelno">
        <el-input
          v-model="queryParams.modelno"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="关联流程" prop="wid">
              <el-select v-model="queryParams.wid" placeholder="选择流程">
                <el-option
                  v-for="item in workflows"
                  :key="item.wid"
                  :label="item.name"
                  :value="item.wid"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>

      <el-form-item label="业务类型" prop="busstype">
        <el-select v-model="queryParams.busstype" placeholder="请选择业务类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.obj_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.glo_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:sysModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:sysModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:sysModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:sysModel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sysModelList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="模型id" align="center" prop="modelid" v-if="true"/> -->
      <el-table-column label="编号" align="center" prop="modelno" />
      <el-table-column label="业务类型" align="center" prop="busstype">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.obj_type" :value="scope.row.busstype"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="流程" align="center" prop="workflow" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_del_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="适用部门id" align="center" prop="deptids" /> -->
      <!-- <el-table-column label="租户id" align="center" prop="tenantId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:sysModel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:sysModel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业务模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="980px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
    <el-row :gutter="15">
    <el-col :span="8">
      <el-form-item label="编号" prop="modelno">
        <el-input v-model="form.modelno" placeholder="请输入编号" />
      </el-form-item>
    </el-col>
     <el-col :span="8">
       <el-form-item label="名称" prop="name">
         <el-input v-model="form.name" placeholder="请输入名称" />
       </el-form-item>
     </el-col>
      <el-col :span="8">
          <el-form-item label="业务类型" prop="busstype">
            <el-select v-model="form.busstype" placeholder="请选择业务类型">
              <el-option
                v-for="dict in dict.type.obj_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="15">
      <el-col :span="8">
            <el-form-item label="关联流程" prop="wid">
              <el-select v-model="form.wid" placeholder="选择流程">
                <el-option
                  v-for="item in workflows"
                  :key="item.wid"
                  :label="item.name"
                  :value="item.wid"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
      </el-col>

    <el-col :span="8">
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.glo_status"
              :key="dict.value"
:label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
</el-col>
    </el-row>
    <el-row :gutter="15">
      <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
              </el-form-item>
      </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>关联表单</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleOpenItemDialog()">添加</el-button>
          </div>
          <div>
          <el-table v-loading="loading" :data="form.items">
            <el-table-column label="名称" align="center" prop="name" />
           <el-table-column label="类型" align="center" prop="typeName" />
           <el-table-column label="排序" align="center" prop="sort" />
           <el-table-column label="值类型" align="center" prop="valueType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.value_type" :value="scope.row.valueType"/>
             </template>
           </el-table-column>
           <el-table-column label="展示类型" align="center" prop="htmlType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.html_type" :value="scope.row.htmlType"/>
             </template>
           </el-table-column>
           <el-table-column label="备注" align="center" prop="remark" />
           <el-table-column label="项类型" align="center" prop="itemType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.item_type" :value="scope.row.itemType"/>
             </template>
           </el-table-column>
           <el-table-column label="重大隐患" align="center" prop="isMajor">
             <template slot-scope="scope">
                 <dict-tag :options="dict.type.is_major" :value="scope.row.isMajor"/>
               </template>
             </el-table-column>
           <el-table-column label="选择项" align="center" prop="selectText" />
           <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" >
             <template slot-scope="scope">
               <el-button
                 size="mini"
                 type="text"
                 icon="el-icon-delete"
                 @click="handleDeleteItem(scope.row,scope.$index)"
                 v-hasPermi="['system:sysModel:edit']"
               >删除</el-button>
             </template>
           </el-table-column>
         </el-table>
          </div>
        </el-card>
      </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog
            width="80%"
            title="选择表单项"
            :visible.sync="drawer"
            append-to-body>
             <el-row :gutter="15">
              <el-col :span="8">
                <el-tree
                   :data="typeOptions"
                   :props="defaultProps"
                   :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   ref="tree"
                   default-expand-all
                   @node-click="handleNodeClick"
                />
              </el-col>
              <el-col :span="16">
          <el-table ref="itemTable" v-loading="loading" :data="sysCheckItemList"
          @selection-change="ihandleSelectionChange">
           <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="名称" align="center" prop="name" />
           <el-table-column label="类型" align="center" prop="typeName" />
           <el-table-column label="排序" align="center" prop="sort" />
           <el-table-column label="值类型" align="center" prop="valueType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.value_type" :value="scope.row.valueType"/>
             </template>
           </el-table-column>
           <el-table-column label="展示类型" align="center" prop="htmlType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.html_type" :value="scope.row.htmlType"/>
             </template>
           </el-table-column>
           <el-table-column label="项类型" align="center" prop="itemType">
             <template slot-scope="scope">
               <dict-tag :options="dict.type.item_type" :value="scope.row.itemType"/>
             </template>
           </el-table-column>
           <el-table-column label="重大隐患" align="center" prop="isMajor">
             <template slot-scope="scope">
                 <dict-tag :options="dict.type.is_major" :value="scope.row.isMajor"/>
               </template>
             </el-table-column>
           <el-table-column label="选择项" align="center" prop="selectText" />
         </el-table>

         <pagination
           v-show="itotal>0"
           :total="itotal"
           :page.sync="iqueryParams.pageNum"
           :limit.sync="iqueryParams.pageSize"
           @pagination="getIList"
         />
              </el-col>
             </el-row>
             <div slot="footer" class="dialog-footer">
                 <el-button @click="dialogFormVisible">关 闭</el-button>
                 <el-button type="primary" @click="dialogFormSure">添 加</el-button>
               </div>
          </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { listSysModel, getSysModel, delSysModel, addSysModel, updateSysModel } from "@/api/system/sysModel";
import { listSysWorkflow } from "@/api/system/sysWorkflow";
import { listSysForm } from "@/api/system/sysForm";
import { listSysCheckType,treeselect } from "@/api/system/sysCheckType";
import { listSysCheckItem } from "@/api/system/sysCheckItem";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SysModel",
  dicts: ['obj_type', 'glo_status','item_type', 'html_type', 'value_type', 'is_major','sys_del_flag'],
  components: { Treeselect },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      drawer:false,
      // 总条数
      total: 0,
      // 业务模型表格数据
      sysModelList: [],
      itotal: 0,
      sysCheckItemList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //工作流程选项
      workflows:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelno: undefined,
        busstype: undefined,
        name: undefined,
        wid: undefined,
        status: undefined,
      },
      iqueryParams: {
        pageNum: 1,
        pageSize: 1000,
        name: undefined,
        typeId: undefined,
        valueType: undefined,
        htmlType: undefined,
        status: undefined,
        itemType: undefined,
        isMajor: undefined,
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      iids:[],
      typeTreeOptions:[],
      typeOptions:[],
      formItems:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getWorkflows();
  },
  methods: {
    /** 查询业务模型列表 */
    getList() {
      this.loading = true;
      listSysModel(this.queryParams).then(response => {
        this.sysModelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWorkflows(){
      listSysWorkflow().then(response => {
        this.workflows = response.rows;
      });
    },
    getIList() {
      this.loading = true;
      listSysCheckItem(this.iqueryParams).then(response => {
        this.sysCheckItemList = response.rows;
        this.itotal = response.itotal;
        this.loading = false;
      });
    },
    getTypeTree(){
      treeselect().then(response => {
        this.typeOptions = response.data
      });
    },
    /** 转换类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.name,
        children: node.children
      };
    },
    getCheckItems(){
      this.loading = true;
      listSysCheckItem(this.iqueryParams).then(response => {
        this.sysCheckItemList = response.rows;
        this.itotal = response.total;
        this.loading = false;
      });
    },
    handleDeleteItem(row,rowIndex){
      this.form.items.splice(rowIndex, 1)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.iqueryParams.typeId = data.id;
      this.iqueryParams.pageNum = 1;
      this.getCheckItems();
    },
    dialogFormSure(){
      console.info(this.$refs.itemTable.selection)
      let formItems = this.form.items || [];
      this.$refs.itemTable.selection.forEach(function(item){
          let flag = false;
          formItems.forEach(function(citem){
            if(citem.itemId == item.itemId){
              flag = true;
            }
          });
          if(!flag){
            formItems.push(item);
          }
        });
      this.form.items = formItems;
    },
    dialogFormVisible(){
      this.drawer = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelid: undefined,
        modelno: undefined,
        busstype: undefined,
        name: undefined,
        wid: undefined,
        remark: undefined,
        status: "0",
        deptids: undefined,
        tenantId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        items:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    ihandleSelectionChange(selection) {
      this.iids = selection.map(item => item.itemId)
    },
    handleOpenItemDialog(){
      this.getTypeTree();
      this.getCheckItems();
      this.drawer = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业务模型";
      treeselect().then(response => {
        this.typeTreeOptions = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const modelid = row.modelid || this.ids
      treeselect().then(response => {
        this.typeTreeOptions = this.handleTree(response.data, "typeId");
      });
      getSysModel(modelid).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改业务模型";
      });
      listSysForm(Object({mid:modelid})).then(response => {
          this.form.items = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.modelid != null) {
            updateSysModel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addSysModel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelids = row.modelid || this.ids;
      this.$modal.confirm('是否确认删除业务模型编号为"' + modelids + '"的数据项？').then(() => {
        this.loading = true;
        return delSysModel(modelids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sysModel/export', {
        ...this.queryParams
      }, `sysModel_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
